import re

# 1.查找第一个符合匹配的字符串
ret1 = re.search(r"\d+", "阅读次数为 9999")
print(ret1.group())                                             # "999"

# 2.查找所有符合匹配的字符串
ret2 = re.findall(r"\d+", "python = 9999, c = 7890, c++ = 12345")
print(ret2)                                                     # ['9999', '7890', '12345']

# 3.替换符合匹配规则的字符串
ret3 = re.sub(r"\d+", '1024', "python = 997")
print(ret3)                                                     # "python = 1024"

# 3.1 替换保留分组内容
ret3_1 = re.sub(r'(\d+)', r'\1zzz','222ggg')                    # '222zzzggg'
print(ret3_1)

# 3.2 替换分组
ret3_2 = re.sub(r'(\w+):((\w|-)+)', r'{\1,\2}', 'name:Task-1')  # {name,Task-1}
print(ret3_2)

# 4.匹配分割符
ret4 = re.split(r":| ","info:xiaoZhang 33 shandong")
print(ret4)                                                     # ['info', 'xiaoZhang', '33', 'shandong']

# 5.finditer行为跟findall类似, 只不过返回的不是列表而是Match对象的迭代器
ret5 = re.finditer(r"\d+", "python = 9999, c = 7890, c++ = 12345")
for matchobj in ret5:
    print(matchobj.group())
    print(matchobj.span())